<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ style: { width: '70px' } }"
    :wrapper-col="{ style: { width: 'auto' } }"
    autocomplete="off"
    ref="refForm"
  >
    <a-form-item
      label="用户名"
      name="username"
      :rules="[{ required: true, message: '请输入用户名' }]"
    >
      <a-input v-model:value="formState.username" placeholder="请输入用户名" />
    </a-form-item>
    <a-form-item label="账号" name="account" :rules="[{ required: true, message: '请输入账号' }]">
      <a-input v-model:value="formState.account" placeholder="请输入用户名" />
    </a-form-item>
    <a-form-item
      v-if="props.hidePassword"
      label="密码"
      name="password"
      :rules="[{ required: true, message: '请输入密码' }]"
    >
      <a-input v-model:value="formState.password" type="password" placeholder="请输入密码" />
    </a-form-item>
    <a-form-item label="角色" name="roleId" :rules="[{ required: true, message: '请选择角色' }]">
      <a-select
        v-model:value="formState.roleId"
        show-search
        style="width: 100%"
        placeholder="Select users"
        :filter-option="false"
        :not-found-content="state.fetching ? undefined : null"
        :options="state.data"
        @search="fetchUser"
      >
        <template v-if="state.fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </a-form-item>
    <a-form-item label="头像" name="avatar" :rules="[{ required: true, message: '请选择头像' }]">
      <a-upload
        name="avatar"
        list-type="picture-card"
        :show-upload-list="false"
        :before-upload="beforeUpload"
      >
        <img
          style="width: 100%; height: 100%; object-fit: cover"
          v-if="formState.avatar"
          :src="formState.avatar"
          alt="avatar"
        />
        <div v-else>
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
    </a-form-item>
    <a-form-item
      label="验证码"
      name="captchaCode"
      :rules="[{ required: true, message: '请输入验证码' }]"
      v-if="hidePassword"
    >
      <a-row>
        <a-col :span="12">
          <a-input v-model:value="formState.captchaCode" placeholder="请输入验证码" />
        </a-col>
        <a-col :span="12">
          <div class="custom-captcha" @click="getCaptcha" v-html="captcha.svg"></div>
        </a-col>
      </a-row>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref, defineProps, reactive } from 'vue'
import type { CreateUserDto } from '@/api/user.api.ts'
import { message } from 'ant-design-vue'
import { getCaptchaApi } from '@/api/auth.api.ts'
import { debounce } from 'lodash-es'
import { getRolesListApi } from '@/api/role.api.ts'

const props = defineProps({
  hidePassword: {
    type: Boolean,
    default: true,
  },
})

const formState = ref<CreateUserDto>({
  account: '',
  password: '',
  username: '',
  avatar: '',
  captchaId: '', // 新增：验证码 ID
  captchaCode: '', // 新增：验证码值
  roleId: '',
})

const captcha = ref({
  captchaId: undefined,
  svg: undefined,
})

const refForm = ref()
const submit = () => {
  return refForm.value.validateFields().then(() => {
    return { ...formState.value, avatarFile }
  })
}

const clearFormState = () => {
  getCaptcha()
  getRoleList()
  avatarFile = null;
  return refForm.value.resetFields()
}

const setFormState = (record: CreateUserDto) => {
  formState.value = record
  formState.value.roleId = formState.value.role?.id;
  avatarFile = null;
  getRoleList()
  getCaptcha()
}

let avatarFile: File | null;
const beforeUpload = (file: File) => {
  if (!file) return
  // 检查文件类型是否为图片
  if (!file.type.startsWith('image/')) {
    message.info('请选择有效的图片文件')
    return
  }
  // 限制文件大小（示例限制为2MB）
  const maxSize = 1024 * 1024 // 2MB
  if (file.size > maxSize) {
    message.info('文件大小不能超过1MB')
    return
  }
  avatarFile = file

  const reader = new FileReader()
  reader.readAsDataURL(file) // 关键转换方法
  reader.onload = function (event: ProgressEvent<FileReader>) {
    // 类型安全访问结果
    if (!event.target?.result) {
      message.info('文件读取结果为空')
      return
    }
    // 明确类型为字符串（Data URL格式）
    const base64String: string = event.target.result as string
    // 提取纯Base64部分
    const [metaPart, dataPart] = base64String.split(',')
    if (!dataPart) {
      message.info('无效的Data URL格式')
      return
    }
    const pureBase64: string = dataPart
    // 可选：验证MIME类型
    const mimeTypeMatch = metaPart.match(/^data:(image\/\w+);base64$/)
    if (!mimeTypeMatch) {
      message.info('不支持的文件类型')
      return
    }
    const mimeType = mimeTypeMatch[1]
    formState.value.avatar = `data:${mimeType};base64,${pureBase64}`
    refForm.value.validateFields('avatar')
  }
  return false

  // const formData = new FormData()
  // formData.append('file', file)
  // localhostUpload(formData).then((res) => {
  //   formState.value.avatar = res.fileUrl;
  //   refForm.value.validateFields('avatar')
  // })
  // return false;
}

const getCaptcha = () => {
  getCaptchaApi().then((res) => {
    captcha.value = res
    formState.value.captchaId = captcha.value.captchaId
  })
}

const state = reactive({
  data: [],
  value: undefined,
  fetching: false,
})

const getRoleList = (value: string = '') => {
  getRolesListApi({ pageNo: 1, pageSize: 10, name: value ?? '' }).then((res) => {
    state.data = res.records.map((v) => {
      return {
        label: v.name,
        value: v.id,
      }
    })
    state.fetching = false
  })
}
const fetchUser = debounce((value) => {
  state.data = []
  state.fetching = true
  getRoleList(value)
}, 300)

defineExpose({
  submit,
  clearFormState,
  setFormState,
})

defineOptions({
  name: 'RoleEditForm',
})
</script>
<style scoped>
.custom-captcha {
  height: 32px;
}
.custom-captcha > :deep(svg) {
  width: 100%;
  height: 100%;
}
</style>
